package com.recharge.controller;

import com.recharge.base.ResponseInfo;
import com.recharge.base.ResponseInfoEnum;
import com.recharge.wk.domain.TradeMerchant;
import com.recharge.wk.mapper.ITradeMerchantMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by qi.cao on 2017/1/23.
 */
@Controller
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private ITradeMerchantMapper iTradeMerchantMapper;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request,@RequestParam("merId")String merId,@RequestParam("password")String password,
                              @RequestParam("userCode")String userCode){
        ResponseInfo responseInfo = new ResponseInfo();
        String rand = (String) WebUtils.getSessionAttribute(request, "rand");

        if (!StringUtils.equals(rand,userCode)){
            logger.info("userCode is error .merId :{}",merId);
            responseInfo.setInfoEnum(ResponseInfoEnum.FAIL);
            WebUtils.setSessionAttribute(request, "login_error", "验证码错误");
            return new ModelAndView("redirect:/index.jsp");
        }



        TradeMerchant tradeMerchant = iTradeMerchantMapper.selectById(merId, DigestUtils.md5Hex(password));
        if (tradeMerchant==null){
            logger.info("login error . merId:{}",merId);
            WebUtils.setSessionAttribute(request, "login_error","用户名或者密码错误");
            return new ModelAndView("redirect:/index.jsp");
        }

        WebUtils.setSessionAttribute(request, "LOGIN_KEY" ,tradeMerchant);
        responseInfo.setInfoEnum(ResponseInfoEnum.SUCCESS);
        return new ModelAndView("redirect:/main.jsp");
    }


    @RequestMapping("/loginOut")
    public ModelAndView loginOut(HttpServletRequest request){
        ResponseInfo responseInfo = new ResponseInfo();
        WebUtils.setSessionAttribute(request, "LOGIN_KEY" ,null);
        responseInfo.setInfoEnum(ResponseInfoEnum.SUCCESS);
        return new ModelAndView("redirect:/index.jsp");
    }
}
